﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
struct NetPosData
{
    public uint serverFrame;
    public Vector3 pos;
    public NetPosData(uint _serverFrame, Vector3 _pos)
    {
        serverFrame = _serverFrame;
        pos = _pos;
    }
}
public class NetPosComponent : MonoBehaviour
{
    private bool interpolatingLocalToClientNetPos = false;
    public float localSimulateMaxDelta = 0.2f;
    //本地模拟的物体
    public Transform localTrans;
    private List<NetPosData> stateList = new List<NetPosData>();
    private NetPosData nextState = new NetPosData(0, Vector3.zero);
    private NetPosData lastState = new NetPosData(0, Vector3.zero);

    public void SyncPos(uint serverFrame, Vector3 nextPos)
    {
        NetPosData netPosData = new NetPosData(serverFrame, nextPos);
        stateList.Add(netPosData);
    }

    public void Simulate(uint remoteEstimatedFrame)
    {
        if (remoteEstimatedFrame >= nextState.serverFrame)
        {
            lastState = nextState;
            //直接将位置设置到nextState
            transform.position = lastState.pos;
            //删掉nextState之前的状态
            var index = stateList.IndexOf(lastState);
            stateList.RemoveRange(0, index + 1); // 删掉应用过的状态前面的状态
            //当下一个状态到来时，nextState将是它
            if (stateList.Count > 0)
            {
                nextState = stateList[0];
            }
        }
        else // 插值当前状态到下一个状态
        {
            float lerp_factor = (remoteEstimatedFrame - lastState.serverFrame) * 1.0f / (nextState.serverFrame - lastState.serverFrame);
            var lerp_position = Vector3.Lerp(lastState.pos, nextState.pos, lerp_factor);
            transform.position = lerp_position;
        }

    }

    private IEnumerator InterpolatingLocalToServer()
    {
        yield return new WaitForSeconds(0.3f);
        localTrans.GetComponent<Rigidbody>().velocity = Vector3.zero;
        var interpolatingTime = 0.2f;
        for (float ft = interpolatingTime; ft >= 0; ft -= 0.02f)
        {
            float lerp_factor = (interpolatingTime - ft) / interpolatingTime;
            var lerp_position = Vector3.Lerp(localTrans.position, transform.position, lerp_factor);
            localTrans.position = lerp_position;
            yield return new WaitForSeconds(0.02f);
        }
        interpolatingLocalToClientNetPos = false;
        yield return null;
    }


}
